// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/dwio/common/selective_integer_column_reader.h>
#include <pollux/dwio/dwrf/common/decoder_util.h>
#include <pollux/dwio/dwrf/reader/dwrf_data.h>

namespace kumo::pollux::dwrf {

class SelectiveIntegerDictionaryColumnReader
    : public dwio::common::SelectiveIntegerColumnReader {
 public:
  using ValueType = int64_t;

  SelectiveIntegerDictionaryColumnReader(
      const TypePtr& requestedType,
      std::shared_ptr<const dwio::common::TypeWithId> fileType,
      DwrfParams& params,
      common::ScanSpec& scanSpec,
      uint32_t numBytes);

  void seekToRowGroup(int64_t index) override {
    SelectiveIntegerColumnReader::seekToRowGroup(index);
    auto positionsProvider = formatData_->seekToRowGroup(index);
    if (inDictionaryReader_) {
      inDictionaryReader_->seekToRowGroup(positionsProvider);
    }

    dataReader_->seekToRowGroup(positionsProvider);
    POLLUX_CHECK(!positionsProvider.hasNext());
  }

  uint64_t skip(uint64_t numValues) override;

  void read(int64_t offset, const RowSet& rows, const uint64_t* incomingNulls)
      override;

  template <typename ColumnVisitor>
  void readWithVisitor(const RowSet& rows, ColumnVisitor visitor);

 private:
  void ensureInitialized();

  std::unique_ptr<ByteRleDecoder> inDictionaryReader_;
  std::unique_ptr<dwio::common::IntDecoder</*isSigned=*/false>> dataReader_;
  std::function<BufferPtr()> dictInit_;
  RleVersion rleVersion_;
  bool initialized_{false};
};

template <typename ColumnVisitor>
void SelectiveIntegerDictionaryColumnReader::readWithVisitor(
    const RowSet& /*rows*/,
    ColumnVisitor visitor) {
  auto dictVisitor = visitor.toDictionaryColumnVisitor();
  if (rleVersion_ == RleVersion_1) {
    decodeWithVisitor<pollux::dwrf::RleDecoderV1<false>>(
        dataReader_.get(), dictVisitor);
  } else {
    decodeWithVisitor<pollux::dwrf::RleDecoderV2<false>>(
        dataReader_.get(), dictVisitor);
  }
}
} // namespace kumo::pollux::dwrf
